package com.itheima.controller.interceptor;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器是给SpringMvc服务的，SpringMvc要加载到他
 * 所以要声明成bean对象     -->注册的时候要用到他
 *
 *
 *
 * 1.自己在controller包下定义一个拦截器类    -->实现HandlerInterceptor接口，重写三个方法
 * 2.将拦截器类加上@Component成为SpringMvc的bean
 * 3.SpringMvcConfig中的@ComponentScan中要扫到这个类
 * 4.添加一个SpringMvcSupport配置类,继承WebMvcConfigurationSupport类，其实就是之前防止金泰页面被拦截的那个配置
 * 5.重写addInterceptor方法，调用registry中的方法
 * 6.让SpringMvc能扫描得到他，在@ComponentScan中添加，另外自己也加@Configuration注解
 */
@Component
public class ProjectInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String contextType = request.getHeader("Content-Type");
        System.out.println("preHandle..." + contextType);

        //handler其实就是封装了现在执行的这个方法
        System.out.println(handler);

        HandlerMethod hm = (HandlerMethod) handler;
        hm.getMethod();
        return true;
    }

    public  void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //modelAndView用于页面跳转

        System.out.println("postHanle...");
    }

    public  void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //ex封装了原始方法的异常信息

        System.out.println("afterCompletion...");
    }

}
